
package cn.com.gome.generator.logic;

import cn.com.gome.framework.dao.entity.TblChildProjectInfo;
import cn.com.gome.framework.dao.entity.TblProjectBasicInfo;
import com.gomeplus.frame.exception.LogicsException;
import com.gomeplus.frame.logic.ILogics;
import com.gomeplus.frame.logic.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;

/**
 * @author chenmin-ds
 * @ClassName: MainProjectCreateLogic
 * @Description: 主项目创建
 * @date 2017年5月26日 下午2:49:05
 */
@Service
public class ChildProjectServiceCreateLogic extends AbstractLogic implements ILogics<Map<String, Object>> {

    private Logger logger = LoggerFactory.getLogger("ChildProjectAdminCreateLogic");

    public ResultEnum exec(Map<String, Object> map) throws LogicsException {
        try {
            TblChildProjectInfo childProjectInfo = (TblChildProjectInfo) map.get("childProjectInfo");
            TblProjectBasicInfo projectBasicInfo = (TblProjectBasicInfo) map.get("projectBasicInfo");
            String pachagesPath = projectBasicInfo.getPackages().replace(".", "//");

            String projectPath = projectBasicInfo.getProjectPath().trim();
            if (!projectPath.endsWith("//")) {
                projectPath += "//";
                projectBasicInfo.setProjectPath(projectPath);
            }

            projectPath += projectBasicInfo.getProjectEng() + "//";
            projectPath += projectBasicInfo.getProjectEng() + "-" + childProjectInfo.getChildProjectEng();
            childProjectInfo.setProjectPath(projectPath);
            File file = new File(projectPath + "//src//main//resources//spring.xml");
            if (!file.exists()) {
                file.createNewFile();
            }
            StringBuffer sb = new StringBuffer();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n");
            sb.append("<beans xmlns=\"http://www.springframework.org/schema/beans\" \n");
            sb.append("			xmlns:util=\"http://www.springframework.org/schema/util\" \n");
            sb.append("			xmlns:aop=\"http://www.springframework.org/schema/aop\" \n");
            sb.append("			xmlns:context=\"http://www.springframework.org/schema/context\" \n");
            sb.append("			xmlns:tx=\"http://www.springframework.org/schema/tx\" \n");
            sb.append("			xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n");
            sb.append("			xmlns:mongo=\"http://www.springframework.org/schema/data/mongo\" \n");
            sb.append("			xmlns:task=\"http://www.springframework.org/schema/task\" \n");
            sb.append("			xsi:schemaLocation=\"http://www.springframework.org/schema/aop \n");
            sb.append("								http://www.springframework.org/schema/aop/spring-aop.xsd \n");
            sb.append("								http://www.springframework.org/schema/beans \n");
            sb.append("								http://www.springframework.org/schema/beans/spring-beans.xsd\n");
            sb.append("								http://www.springframework.org/schema/context \n");
            sb.append("								http://www.springframework.org/schema/context/spring-context.xsd \n");
            sb.append("								http://www.springframework.org/schema/tx \n");
            sb.append("								http://www.springframework.org/schema/tx/spring-tx.xsd \n");
            sb.append("								http://www.springframework.org/schema/task \n");
            sb.append("								http://www.springframework.org/schema/task/spring-task-3.1.xsd \n");
            sb.append("								http://www.springframework.org/schema/util \n");
            sb.append("								http://www.springframework.org/schema/util/spring-util-3.1.xsd\">\n");
            sb.append("  \n");
            sb.append("  <aop:aspectj-autoproxy proxy-target-class=\"true\" /> \n");
            sb.append("  <context:annotation-config /> \n");
            if ("com.gomeplus".equals(projectBasicInfo.getPackages())) {
                sb.append("  <context:component-scan base-package=\"com.gomeplus\" /> \n");
            } else {
                sb.append("  <context:component-scan base-package=\"" + projectBasicInfo.getPackages() + ",com.gomeplus\" /> \n");
            }
            sb.append("  \n");
            sb.append("  <bean id=\"springBeanFactory\" class=\"com.gomeplus.frame.factory.SpringBeanFactory\" /> \n");
            sb.append("  \n");
            sb.append("  <import resource=\"classpath*:/spring/" + projectBasicInfo.getProjectEng() + "-jdbc-props.xml\" /> \n");
            sb.append("  <import resource=\"classpath*:/spring/" + projectBasicInfo.getProjectEng() + "-dataSource.xml\" /> \n");
            sb.append("  \n");
            sb.append("  <import resource=\"classpath*:/dubbo/dubbo-head.xml\" /> \n");
            sb.append("  <import resource=\"spring/" + projectBasicInfo.getProjectEng() + "-dubbo-provider.xml\" /> \n");
            sb.append("  <import resource=\"spring/redis-dubbo-consumer.xml\" /> \n");
            sb.append("</beans>\n");
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(projectPath + "//src//main//resources//spring.xml"), "UTF-8");
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            file = new File(projectPath + "//src//main//resources//log4j.properties");
            if (!file.exists()) {
                file.createNewFile();
            }
            sb = new StringBuffer();
            sb.append("log4j.rootLogger=DEBUG,stdout,fileAppender\n");
            sb.append("log4j.logger." + projectBasicInfo.getPackages() + "." + projectBasicInfo.getProjectEng() + ".dao.mapper=DEBUG,ibatis \n");
            sb.append("log4j.logger." + projectBasicInfo.getPackages() + "." + projectBasicInfo.getProjectEng() + ".dubbo.impl=INFO,dubbo \n");
            sb.append("\n");
            sb.append("log4j.appender.stdout=org.apache.log4j.ConsoleAppender\n");
            sb.append("log4j.appender.stdout.layout=org.apache.log4j.PatternLayout\n");
            sb.append("log4j.appender.stdout.DatePattern='_'yyyy-MM-dd'.log'\n");
            sb.append("log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH\\:mm\\:ss SSS} %p [%c] %m%n\n");
            sb.append("\n");
            sb.append("log4j.appender.fileAppender=org.apache.log4j.DailyRollingFileAppender\n");
            sb.append("log4j.appender.fileAppender.File=../logs/" + projectBasicInfo.getProjectEng() + "_service_info.log\n");
            sb.append("log4j.appender.fileAppender.DatePattern='_'yyyy-MM-dd'.log'\n");
            sb.append("log4j.appender.fileAppender.Threshold=INFO\n");
            sb.append("log4j.appender.fileAppender.Encoding=UTF-8\n");
            sb.append("log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout\n");
            sb.append("log4j.appender.fileAppender.layout.ConversionPattern=%-d{yyyyMMdd HH:mm:ss SSS}-->[%-5p]--[%c{1}]--%m%\n");
            sb.append("\n");
            sb.append("log4j.appender.ibatis=org.apache.log4j.DailyRollingFileAppender\n");
            sb.append("log4j.appender.ibatis.File=../logs/" + projectBasicInfo.getProjectEng() + "_service_ibatis.log\n");
            sb.append("log4j.appender.ibatis.DatePattern='_'yyyy-MM-dd'.log'\n");
            sb.append("log4j.appener.ibatis.Threshold=DEBUG\n");
            sb.append("log4j.appender.ibatis.Encoding=UTF-8\n");
            sb.append("log4j.appender.ibatis.layout=org.apache.log4j.PatternLayout\n");
            sb.append("log4j.appender.ibatis.layout.ConversionPattern=%-d{yyyyMMdd HH:mm:ss SSS}-->[%-5p]--[%c{1}]--%m%nd\n");
            sb.append("\n");
            sb.append("log4j.appender.dubbo=org.apache.log4j.DailyRollingFileAppender\n");
            sb.append("log4j.appender.dubbo.File=../logs/" + projectBasicInfo.getProjectEng() + "_service_dubbo.log\n");
            sb.append("log4j.appender.dubbo.DatePattern='_'yyyy-MM-dd'.log'\n");
            sb.append("log4j.appener.dubbo.Threshold=INFO\n");
            sb.append("log4j.appender.dubbo.Encoding=UTF-8\n");
            sb.append("log4j.appender.dubbo.layout=org.apache.log4j.PatternLayout\n");
            sb.append("log4j.appender.dubbo.layout.ConversionPattern=%-d{yyyyMMdd HH:mm:ss SSS}-->[%-5p]--[%c{1}]--%m%nd\n");

            write = new OutputStreamWriter(new FileOutputStream(projectPath + "//src//main//resources//log4j.properties"), "UTF-8");
            writer = new BufferedWriter(write);
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            file = new File(projectPath + "//src//main//resources//spring");
            if (!file.exists()) {
                file.mkdirs();
            }

            file = new File(projectPath + "//src//main//resources//spring//redis-dubbo-consumer.xml");
            if (!file.exists()) {
                file.createNewFile();
            }
            sb = new StringBuffer();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            sb.append("<beans xmlns=\"http://www.springframework.org/schema/beans\"\n");
            sb.append("	xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dubbo=\"http://code.alibabatech.com/schema/dubbo\"\n");
            sb.append("	xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\n");
            sb.append("	http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd\">\n");
            sb.append("	<bean id=\"jjcsGcache\" class=\"redis.GcacheClient\" destroy-method=\"close\">\n");
            sb.append("	<!-- zookeeperAddress -->\n");
            sb.append("	<constructor-arg value=\"${dubbo.run.redis}\" />\n");
            sb.append("	<!-- businessName -->\n");
            sb.append("	<constructor-arg value=\"${redis.businessName}\" />\n");
            sb.append("	</bean>\n");
            sb.append("</beans>\n");
            write = new OutputStreamWriter(new FileOutputStream(projectPath + "//src//main//resources//spring//redis-dubbo-consumer.xml"), "UTF-8");
            writer = new BufferedWriter(write);
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            file = new File(projectPath + "//src//main//resources//spring//" + projectBasicInfo.getProjectEng() + "-dubbo-provider.xml");
            if (!file.exists()) {
                file.createNewFile();
            }
            sb = new StringBuffer();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n");
            sb.append("<beans xmlns=\"http://www.springframework.org/schema/beans\" \n");
            sb.append("			xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n");
            sb.append("			xmlns:dubbo=\"http://code.alibabatech.com/schema/dubbo\" \n");
            sb.append("			xsi:schemaLocation=\"http://www.springframework.org/schema/beans \n");
            sb.append("				http://www.springframework.org/schema/beans/spring-beans-2.5.xsd \n");
            sb.append("				http://code.alibabatech.com/schema/dubbo \n");
            sb.append("				http://code.alibabatech.com/schema/dubbo/dubbo.xsd\">\n");
            sb.append("  <dubbo:consumer check=\"false\" /> \n");
            sb.append("  <dubbo:registry protocol=\"zookeeper\" address=\"${dubbo.run.registryAddress}\" id=\"" + projectBasicInfo.getProjectEng() + "DubboProvider\" /> \n");
            sb.append("  <dubbo:protocol name=\"dubbo\" port=\"-1\" /> \n");
            sb.append("  \n");
            sb.append("  <!--dubbo:service timeout=\"6000\" group=\"${dubbo.group}\" ref=\"couponFacadeServiceImpl\" interface=\"com.gome.mammon.dubbo.CouponFacadeService\" registry=\"" + projectBasicInfo.getProjectEng() + "DubboProvider\" /-->\n");
            sb.append("   \n");
            sb.append("</beans>\n");
            write = new OutputStreamWriter(new FileOutputStream(projectPath + "//src//main//resources//spring//" + projectBasicInfo.getProjectEng() + "-dubbo-provider.xml"), "UTF-8");
            writer = new BufferedWriter(write);
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            file = new File(projectPath + "//src//main//resources//props//dev");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//resources//props//dev//" + projectBasicInfo.getProjectEng() + "-service.properties");
            if (!file.exists()) {
                file.createNewFile();
            }
            file = new File(projectPath + "//src//main//resources//props//uat");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//resources//props//uat//" + projectBasicInfo.getProjectEng() + "-service.properties");
            if (!file.exists()) {
                file.createNewFile();
            }
            file = new File(projectPath + "//src//main//resources//props//live");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//resources//props//live//" + projectBasicInfo.getProjectEng() + "-service.properties");
            if (!file.exists()) {
                file.createNewFile();
            }
            file = new File(projectPath + "//src//main//resources//props//pre");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//resources//props//pre//" + projectBasicInfo.getProjectEng() + "-service.properties");
            if (!file.exists()) {
                file.createNewFile();
            }

            file = new File(projectPath + "//src//main//resources//props//" + projectBasicInfo.getProjectEng() + "-service.properties");
            if (!file.exists()) {
                file.createNewFile();
            }

            file = new File(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//dubbo//impl");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//logic//impl");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//service//impl");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//utils");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//cache");
            if (!file.exists()) {
                file.mkdirs();
            }

            file = new File(projectPath + "//src//main//webapp//WEB-INF");
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(projectPath + "//src//main//webapp//WEB-INF//web.xml");
            if (!file.exists()) {
                file.createNewFile();
            }
            sb = new StringBuffer();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
            sb.append("<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n");
            sb.append("	xmlns=\"http://java.sun.com/xml/ns/javaee\" \n");
            sb.append("	xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\" \n");
            sb.append("	version=\"2.5\" metadata-complete=\"true\">\n");
            sb.append("  <context-param>\n");
            sb.append("  	<param-name>contextConfigLocation</param-name> \n");
            sb.append("  	<param-value>classpath:spring.xml</param-value> \n");
            sb.append("  </context-param>\n");
            sb.append("  <context-param>\n");
            sb.append("  	<param-name>propertiesConfigLocation</param-name> \n");
            sb.append("  	<param-value>/props/" + projectBasicInfo.getProjectEng() + "-service.properties</param-value>\n");
            sb.append("  </context-param>\n");
            sb.append("  <listener>\n");
            sb.append("  	<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> \n");
            sb.append("  </listener>\n");
            sb.append("  <listener>\n");
            sb.append("  	<listener-class>com.gomeplus.frame.listener.PropertiesConfigListener</listener-class> \n");
            sb.append("  </listener>\n");
            sb.append("  <listener>\n");
            sb.append("  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> \n");
            sb.append("  </listener>\n");
            sb.append("</web-app>\n");
            write = new OutputStreamWriter(new FileOutputStream(projectPath + "//src//main//webapp//WEB-INF//web.xml"), "UTF-8");
            writer = new BufferedWriter(write);
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            file = new File(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//service//impl//SCacheServiceImpl.java");
            if (!file.exists()) {
                file.createNewFile();
            }
            sb = new StringBuffer();
            sb.append("package " + projectBasicInfo.getPackages() + "." + projectBasicInfo.getProjectEng() + ".service.impl;\n");
            sb.append("\n");
            sb.append("import java.util.ArrayList;\n");
            sb.append("import java.util.List;\n");
            sb.append("\n");
            sb.append("import javax.annotation.PostConstruct;\n");
            sb.append("\n");
            sb.append("import org.slf4j.Logger;\n");
            sb.append("import org.slf4j.LoggerFactory;\n");
            sb.append("import org.springframework.stereotype.Service;\n");
            sb.append("\n");
            sb.append("import com.gomeplus.frame.cache.GlobalApplicationCache;\n");
            sb.append("import com.gomeplus.frame.cache.GlobalDataDictionaryCache;\n");
            sb.append("import com.gomeplus.frame.cache.DictionaryVo;\n");
            sb.append("\n");
            sb.append("import " + projectBasicInfo.getPackages() + "." + projectBasicInfo.getProjectEng() + ".service.SCacheService;\n");
            sb.append("\n");
            sb.append("/**\n");
            sb.append(" * @ClassName: CacheServiceImpl\n");
            sb.append(" * @Description: 缓存参数初始化接口实现\n");
            sb.append(" * @author chenmin-ds\n");
            sb.append(" * @date 2015年5月13日 下午4:47:02\n");
            sb.append(" */\n");
            sb.append("@Service\n");
            sb.append("public class SCacheServiceImpl implements SCacheService {\n");
            sb.append("\n");
            sb.append("	private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());\n");
            sb.append("	\n");
            sb.append("	@PostConstruct\n");
            sb.append("	private void inits() {\n");
            sb.append("		logger.info(\"系统启动时初始化静态参数开始...\");\n");
            sb.append("		setSysDic();\n");
            sb.append("		logger.info(\"系统启动时初始化静态参数成功\");\n");
            sb.append("	}\n");
            sb.append("	\n");
            sb.append("	public void cacheUpdate() {\n");
            sb.append("		logger.info(\"系统更新初始化静态参数开始...\");\n");
            sb.append("		setSysDic();\n");
            sb.append("		logger.info(\"系统更新初始化静态参数成功\");\n");
            sb.append("	}\n");
            sb.append("\n");
            sb.append("	private void setSysDic(){\n");
            sb.append("		List<DictionaryVo> list = new ArrayList<DictionaryVo>();\n");
            sb.append("		list.add(new DictionaryVo(\"010\",\"测试1\"));\n");
            sb.append("		list.add(new DictionaryVo(\"020\",\"测试2\"));\n");
            sb.append("		list.add(new DictionaryVo(\"030\",\"测试3\"));\n");
            sb.append("		list.add(new DictionaryVo(\"040\",\"测试4\"));\n");
            sb.append("		GlobalDataDictionaryCache.getInstance().putIdValue(\"TEST_TEST\", list);\n");
            sb.append("	}\n");
            sb.append("}\n");

            write = new OutputStreamWriter(new FileOutputStream(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//service//impl//SCacheServiceImpl.java"), "UTF-8");
            writer = new BufferedWriter(write);
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            file = new File(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//service//SCacheService.java");
            if (!file.exists()) {
                file.createNewFile();
            }
            sb = new StringBuffer();
            sb.append("package " + projectBasicInfo.getPackages() + "." + projectBasicInfo.getProjectEng() + ".service;\n");
            sb.append("\n");
            sb.append("/**\n");
            sb.append(" * @ClassName: CacheServiceImpl\n");
            sb.append(" * @Description: 缓存参数初始化接口实现\n");
            sb.append(" * @author chenmin-ds\n");
            sb.append(" * @date 2015年5月13日 下午4:47:02\n");
            sb.append(" */\n");
            sb.append("public interface SCacheService {\n");
            sb.append("\n");
            sb.append("	public void cacheUpdate();\n");
            sb.append("}\n");
            write = new OutputStreamWriter(new FileOutputStream(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//service//SCacheService.java"), "UTF-8");
            writer = new BufferedWriter(write);
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            String PROJECT_ENG_U = columnToStringU(projectBasicInfo.getProjectEng().trim());
            file = new File(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//cache//" + PROJECT_ENG_U + "Cache.java");
            if (!file.exists()) {
                file.createNewFile();
            }
            sb = new StringBuffer();
            sb.append("/** \n");
            sb.append("* @Title: " + PROJECT_ENG_U + "Cache.java \n");
            sb.append("* @Package " + projectBasicInfo.getPackages() + "." + projectBasicInfo.getProjectEng() + ".cache\n");
            sb.append("* @Description: 应用级缓存\n");
            sb.append("* @author GOME   \n");
            sb.append("* @date " + getCodeGenerateTime() + " \n");
            sb.append("* @company cn.com.gome\n");
            sb.append("* @version V1.0   \n");
            sb.append("*/ \n");
            sb.append("\n");
            sb.append("package " + projectBasicInfo.getPackages() + "." + projectBasicInfo.getProjectEng() + ".cache;\n");
            sb.append("\n");
            sb.append("import java.util.concurrent.ConcurrentMap;\n");
            sb.append("import java.util.concurrent.ConcurrentHashMap;\n");

            sb.append("\n");
            sb.append("/** \n");
            sb.append(" * @ClassName: " + PROJECT_ENG_U + "Cache \n");
            sb.append(" * @Description: 应用级缓存\n");
            sb.append(" * @author GOME \n");
            sb.append(" * @date " + getCodeGenerateTime() + "  \n");
            sb.append(" */\n");
            sb.append("public class " + PROJECT_ENG_U + "Cache {\n");
            sb.append("\n");
            sb.append("	public static ConcurrentMap<String, String> business = new ConcurrentHashMap<String,String>();\n");
            sb.append("	\n");
            sb.append("}\n");
            write = new OutputStreamWriter(new FileOutputStream(projectPath + "//src//main//java//" + pachagesPath + "//" + projectBasicInfo.getProjectEng() + "//cache//" + PROJECT_ENG_U + "Cache.java"), "UTF-8");
            writer = new BufferedWriter(write);
            writer.write(sb.toString());
            writer.flush();
            writer.close();

            return ResultEnum.OK;
        } catch (Exception e) {
            logger.error("创建子项目异常：", e);
        }
        return ResultEnum.PART_CASE_01;
    }

}
